<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/logo.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/logo.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/logo.png">
  <link rel="mask-icon" href="/images/logo.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/","scheme":"Pisces","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"./public/search.xml"};
  </script>

  <meta name="description" content="正则表达式学习笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="正则表达式">
<meta property="og:url" content="https://gitee.com/mamba666/mamba666.git/2020/03/09/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/index.html">
<meta property="og:site_name" content="共你云雨">
<meta property="og:description" content="正则表达式学习笔记">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-03-09T08:46:42.105Z">
<meta property="article:modified_time" content="2020-03-09T08:46:42.939Z">
<meta property="article:author" content="Edison">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://gitee.com/mamba666/mamba666.git/2020/03/09/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>正则表达式 | 共你云雨</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
	<a href="https://github.com/mamba666" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">共你云雨</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/mamba666/mamba666.git/2020/03/09/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Edison">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="共你云雨">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          正则表达式
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-03-09 16:46:42" itemprop="dateCreated datePublished" datetime="2020-03-09T16:46:42+08:00">2020-03-09</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <hr>
<h2 id="正则表达式学习笔记"><a href="#正则表达式学习笔记" class="headerlink" title="正则表达式学习笔记"></a>正则表达式学习笔记</h2><a id="more"></a>

<h2 id="Start"><a href="#Start" class="headerlink" title="Start"></a>Start</h2><pre><code>现在想验证一串美国的邮政编码，格式为十进制代码：99999-9999</code></pre><p>不使用正则表达式代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isThisAZipCode</span>(<span class="params">candidate</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(<span class="keyword">typeof</span> candidate!==<span class="string">"string"</span>||candidate.length!=<span class="number">10</span>)</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">		<span class="built_in">console</span>.log(<span class="string">"false"</span>)		</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">let</span> n=<span class="number">0</span>;n&lt;candidate.length;n++)&#123;</span><br><span class="line">		<span class="keyword">let</span> c=candidate[n]</span><br><span class="line">		<span class="keyword">switch</span>(n)&#123;</span><br><span class="line">			<span class="keyword">case</span> <span class="number">0</span>:</span><br><span class="line">			<span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">			<span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">			<span class="keyword">case</span> <span class="number">3</span>:</span><br><span class="line">			<span class="keyword">case</span> <span class="number">4</span>:</span><br><span class="line">			<span class="keyword">case</span> <span class="number">6</span>:</span><br><span class="line">			<span class="keyword">case</span> <span class="number">7</span>:</span><br><span class="line">			<span class="keyword">case</span> <span class="number">8</span>:</span><br><span class="line">			<span class="keyword">case</span> <span class="number">9</span>:</span><br><span class="line">				<span class="keyword">if</span>(c&lt;<span class="string">"0"</span>||c&gt;<span class="string">"9"</span>)</span><br><span class="line">					<span class="built_in">console</span>.log(<span class="string">"false"</span>)</span><br><span class="line">					<span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">				<span class="keyword">break</span></span><br><span class="line">			<span class="keyword">case</span> <span class="number">5</span>:</span><br><span class="line">				<span class="keyword">if</span>(c!=<span class="string">"-"</span>)</span><br><span class="line">					<span class="built_in">console</span>.log(<span class="string">"false"</span>)</span><br><span class="line">					<span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">				<span class="keyword">break</span></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="string">"true"</span>)</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这种代码看起来很繁琐，这时就可以使用正则表达式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isThisAZipCode</span>(<span class="params">candidate</span>)</span></span><br><span class="line"><span class="function">    <span class="title">return</span> /^\<span class="title">d</span></span>&#123;<span class="number">5</span>&#125;-\d&#123;<span class="number">4</span>&#125;$/.test(candidate)</span><br></pre></td></tr></table></figure>

<h2 id="正则表达式说明"><a href="#正则表达式说明" class="headerlink" title="正则表达式说明"></a>正则表达式说明</h2><pre><code>创建方法
1.字面量表达式
2.创建RegExp的实例

！！！当正则表达式在开发环境是明确的，推荐优先使用字面量语法；当需要在运行时动态创建字符串来构建正则表达式时，则使用构造函数的方式。</code></pre><ul>
<li>5个修饰符<ul>
<li>i 对大小写不敏感</li>
<li>g 查找所有匹配项</li>
<li>m 允许多行匹配</li>
<li>y 开启粘贴匹配</li>
<li>u 允许使用Unicode点转义符</li>
</ul>
</li>
</ul>
<p>在字面量末尾添加修饰符(如/test/ig),或者作为第2个参数传给RegExp构造函数(new RegExp(“ test”, “ig”))</p>
<h2 id="术语和操作符"><a href="#术语和操作符" class="headerlink" title="术语和操作符"></a>术语和操作符</h2><ul>
<li>精确匹配：必须要精准的匹配到完整的字符串    /test/</li>
<li>匹配字符集：<ul>
<li>只需要匹配其中的一个或者多个：[abc]</li>
<li>或者不匹配指定的这几个字符：[^abc]</li>
<li>限定范围：[a-z]</li>
</ul>
</li>
<li>转义：\</li>
<li>起止符号：？？？？</li>
<li>重复出现：如果想匹配4个重复的字符可以使用/aaaa/，那么如果要匹配任意数量的呢？<ul>
<li>指定可选字符（最多出现一次）：/t?est/   —&gt;test,est</li>
<li>指定字符必须出现最少一次：/t+est/     —&gt;test ttest tttest</li>
<li>指定字符必须出现0次1次或者多次：/t*est/     —&gt;est test ttest</li>
<li>指定重复次数：/a{4}/        —&gt;aaaa</li>
<li>指定循环次数的范围：/a{4,10}/        —&gt;aaaa aaaaa … aaaaaaaaaa</li>
<li>指定开放区间：/a{4,}/     —&gt;aaaa aaaaa … aaaaaaaaaaaaaa…</li>
<li>这些运算符都是贪婪的，即会匹配所有的可能，而非贪婪模式则只会进行最小限度的匹配： 如果有字符串aaa那么/a+/会匹配全部的a，如果非贪婪/a+?/那么只会匹配一个a</li>
</ul>
</li>
<li>预定义字符集：有些字符无法通过字面量表达出来<ul>
<li>\t:水平制表符 （相当于tab键）</li>
<li>\b:空格</li>
<li>\r:回车符</li>
<li>\f:换页符</li>
<li>\h:换行符</li>
<li>\d:等价于/0-9/</li>
<li>\D:匹配除了十进制数字外的任意字符。等价于/^0-9/</li>
<li>\w:等价于/0-9a-zA-Z_/</li>
<li>\W:匹配除了字母，下划线，数字。等价于/^0-9a-zA-Z_/</li>
<li>\s:匹配任意空白字符。</li>
<li>\S:匹配除了空白字符以外的任意字符。</li>
<li>\b:匹配单词边界。</li>
<li>\B:匹配单词内部。</li>
</ul>
</li>
</ul>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/js/" rel="tag"># js</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/03/09/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F%E7%AC%94%E8%AE%B0/" rel="prev" title="微信小程序学习笔记">
      <i class="fa fa-chevron-left"></i> 微信小程序学习笔记
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/03/09/%E5%BC%82%E6%AD%A5%E7%BB%84%E4%BB%B6%E5%AE%9E%E7%8E%B0%E6%8C%89%E9%9C%80%E5%8A%A0%E8%BD%BD/" rel="next" title="异步组件实现按需加载">
      异步组件实现按需加载 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#正则表达式学习笔记"><span class="nav-number">1.</span> <span class="nav-text">正则表达式学习笔记</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Start"><span class="nav-number">2.</span> <span class="nav-text">Start</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#正则表达式说明"><span class="nav-number">3.</span> <span class="nav-text">正则表达式说明</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#术语和操作符"><span class="nav-number">4.</span> <span class="nav-text">术语和操作符</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Edison</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">124</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">21</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
</div>
  <div class="powered-by">山高水远  一定相见
  </div>
<div></div>
<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">至今已写107.1k字</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
